<script setup>
import { reactive, onMounted,watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
// 修改导入部分
import { authAPI } from '@/api/user'
import {useUserStore} from "@/stores/user/index.js";

const router = useRouter()
const userStore = useUserStore()

// 表单状态
const formState = reactive({
  username: '',
  password: '',
  tenantId: '',
  clientId: 'campus_web', // 固定客户端ID
  loading: false,
  tenantList: []
})

// 验证规则
const rules = {
  username: [
    { required: true, message: '请输入账号' },
    { match: /^[A-Za-z0-9]{6,12}$/, message: '账号格式不正确' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码至少6位' }
  ],
  tenantId: [
    { required: true, message: '请选择所属机构' }
  ]
}
// 获取租户列表
const fetchTenants = async () => {
  try {
    const {data} = await authAPI.getTenants()
    formState.tenantList = data
    if (data.length > 0) {
      formState.tenantId = data[0]?.id || ''
    }
  } catch (e) {
    // 错误提示已由API层处理，此处可选补充处理
  }
}

// 登录提交
const handleSubmit = async ({ values, errors }) => {
  if (errors) return
  formState.loading = true

  const tenant =  formState.tenantList.filter((tenant)=>{
    if (tenant.id === values.tenantId){
      return tenant
    }
  })

  try {
    userStore.login({
      username: values.username,
      password: values.password,
      tenantId: values.tenantId,
      clientId: values.clientId,
      tenantName: tenant[0].name
    }).then(()=>{
      router.push('/dashboard');
      Message.success('欢迎进入智慧校园')
    })

  }finally {
    formState.loading = false
  }
}

// 初始化获取租户列表
onMounted(fetchTenants)
</script>

<template>
  <div class="campus-login-container">
    <div class="campus-background">
<!--      <img src="@/assets/campus-logo.png" class="campus-logo" alt="校园logo">-->
    </div>

    <a-card class="login-card">
      <h1 class="title">统一认证平台</h1>

      <a-form
          :model="formState"
          :rules="rules"
          layout="vertical"
          @submit="handleSubmit"
      >
        <a-form-item field="tenantId" label="所属机构">
          <a-select
              v-model="formState.tenantId"
              placeholder="请选择机构"
              allow-search
          >
            <a-option
                v-for="tenant in formState.tenantList"
                :key="tenant.id"
                :value="tenant.id"
            >
              {{ tenant.name }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="username" label="账号">
          <a-input
              v-model="formState.username"
              placeholder="请输入账号"
              allow-clear
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="password" label="密码">
          <a-input-password
              v-model="formState.password"
              placeholder="请输入密码"
              allow-clear
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>

        <a-button
            type="primary"
            html-type="submit"
            :loading="formState.loading"
            long
        >
          登录
        </a-button>

        <div class="footer-links">
          <a-link @click="router.push('/forgot-password')">忘记密码？</a-link>
          <a-link @click="router.push('/register')">新用户注册</a-link>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped>
.campus-login-container {
  min-height: 100vh;
  display: flex;
  background: linear-gradient(150deg, #f0f9ff 0%, #ebf5ff 100%);
}

.campus-background {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 或分开写（兼容旧浏览器） */
  background-image: url('@/assets/bg.png');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.campus-logo {
  width: 240px;
  margin-bottom: 40px;
}

.login-card {
  width: 440px;
  min-height: 100vh;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.title {
  text-align: center;
  color: #1677ff;
  margin-bottom: 32px;
  font-size: 24px;
}

.footer-links {
  margin-top: 24px;
  display: flex;
  justify-content: space-between;
}
</style>